/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.ctu.android.DriveCommunicator.listeners;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

/**
 *
 * @author karlos
 */
public class MessageReceiver extends BroadcastReceiver {

    private static String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {

            Bundle bundle = intent.getExtras();
            SmsMessage[] messages = null;
            String from = null;

            if (bundle != null) {
                try {

                    Object[] pdus = (Object[]) bundle.get("pdus");
                    messages = new SmsMessage[pdus.length];

                    String msgBody = null;

                    for (int i = 0; i < messages.length; i++) {
                        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                        from = messages[i].getOriginatingAddress();
                        msgBody = messages[i].getMessageBody();
                    }


                    Toast.makeText(context.getApplicationContext(), from + ":" + msgBody, Toast.LENGTH_LONG).show();
                    
                    // Do some logic, (show new message dialog, etc..)
                    

                } catch (Exception e) {
                    Log.d("Exception caught", e.getMessage());
                }
            }
        }

        // zastavi sireni systemem... (neulozi se do normalnich zprav)
        abortBroadcast();

    }
}
